<template>
  <div class="input-number">
    <button @click="handleDown" :disabled="currentValue <= min" >-</button>
    <input type="text" :value="currentValue" @change="handleChange" @keyup.up='handleUp' @keyup.down='handleDown'> 
    <button @click="handleUp" :disabled="currentValue >= max">+</button>
  </div>
</template>
<script>
export default {
  data(){
    return{
      currentValue: this.value
    }
  },
  props:{
    max: {type: Number, default: Infinity},
    min: {type: Number, default: -Infinity},
    value: {type: Number, default: 0},
    step: {type: Number, default:1},
  },
  methods:{
    handleDown(){
      if(this.currentValue <= this.min) return;
      this.currentValue -= this.step;
    },
    handleUp(){
      if(this.currentValue >= this.max) return;
      this.currentValue += this.step;
    },
    handleChange(){
      let val = event.target.value.trim();
      let max = this.max;
      let min = this.min;
      if(this.isValueNumber(val)){
        val = Number(val);
        this.currentValue = val;
        if(val > max){
          this.currentValue = max;
        } else if(val < min){
          this.currentValue = min;
        }
      } else {
        event.target.value = this.currentValue;
      }
    },
    updateValue(val){
      if(val > this.max) val = this.max;
      if(val < this.min) val = this.min;
      this.currentValue = val;
    },
    isValueNumber(value){
      return (/(^-?[0-9]+\.{1}\d+$) | (^-?[1-9][0-9]*$) | (^-?0{1}$)/).test(value + '');
    }
  },
  mounted(){
    this.updateValue(this.value);
  },
  watch:{
    currentValue(val){
      this.$emit('input', val);
      this.$emit('on-change', val);
    },
    value(val){
      this.updateValue(val);
    }
  }
}
</script>
<style scoped>

</style>


